package com.ukefu.webim.util.impl;

import java.io.IOException;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import com.ukefu.util.ai.AiUtils;
import com.ukefu.webim.service.cache.CacheHelper;
import com.ukefu.webim.util.event.AiMessageSmartProcesser;
import com.ukefu.webim.util.server.message.ChatMessage;
import com.ukefu.webim.web.model.AiUser;
import com.ukefu.webim.web.model.Scene;
import com.ukefu.webim.web.model.SceneItem;

@Component
public class AiMessageSmartProcesserImpl implements AiMessageSmartProcesser{
	
	@SuppressWarnings("unchecked")
	@Override
	public ChatMessage process(ChatMessage message, AiMRoundsProcesserImpl aiMroundsProcesser , AiUser aiUser) {
		ChatMessage retChatMessage = null ;
		try {
			String id = AiUtils.getAiDicTrie().search(message , aiUser) ;
			if(!StringUtils.isBlank(id)){
				List<SceneItem> sceneItemList = (List<SceneItem>) CacheHelper.getSystemCacheBean().getCacheObject(id, message.getOrgi()) ;
				if(sceneItemList!=null &&  sceneItemList.size() >0){
					SceneItem sceneItem = sceneItemList.get(0) ;
					retChatMessage = new ChatMessage();
					retChatMessage.setMessage(sceneItem.getContent());
					retChatMessage.setAppid(message.getAppid());
					retChatMessage.setUserid(aiUser.getUnikey());
					retChatMessage.setUsername("小E");
					retChatMessage.setChannel(message.getChannel());
					retChatMessage.setType(message.getType());
					retChatMessage.setContextid(message.getContextid());
					retChatMessage.setOrgi(message.getOrgi());
					
					/**
					 * 命中结果，记录日志，记录DEBUG信息，下个版本增加功能
					 */
					Scene scene = (Scene) CacheHelper.getSystemCacheBean().getCacheObject("scene."+id, message.getOrgi()) ;
					if(scene!=null && scene.isAccept()) {
						aiMroundsProcesser.process(aiUser, message, scene.getId());
					}
					if(scene!= null && scene.isBussop() && !StringUtils.isBlank(scene.getBusslist())) {
						AiUtils.processAiUserNames(message.getMessage(), scene.getBusslist(), scene.isBussop(), aiUser,scene.getBussclist() , null);
					}
					if(scene.isStaticagent()) {
						retChatMessage.setStaticagent(true);
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return retChatMessage;
	}

}
